//防抖函数
export function debounce(fn, delay = 300) {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

//合同编号
export function generateContract(prefix = "HT", width = 3) {
  const now = new Date();
  const y = now.getFullYear();
  const m = String(now.getMonth() + 1).padStart(2, "0");
  const d = String(now.getDate()).padStart(2, "0");
  const dateStr = `${y}${m}${d}`;

  // 生成 4 位随机大写字母或数字
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  let randPart = "";
  for (let i = 0; i < 4; i++) {
    randPart += chars.charAt(Math.floor(Math.random() * chars.length));
  }

  return `${prefix}-${dateStr}-${randPart}`;
}

export function generateCode(flag) {
  // 当前时间
  const now = new Date();

  // 获取年月日小时（两位数格式）
  const yy = String(now.getFullYear()).slice(2); // 后两位年份
  const mm = String(now.getMonth() + 1).padStart(2, "0");
  const dd = String(now.getDate()).padStart(2, "0");

  const dateCode = `${yy}${mm}${dd}`; // 例如：250604

  // 生成 4 位随机大写字母或数字
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  let randPart = "";
  for (let i = 0; i < 4; i++) {
    randPart += chars.charAt(Math.floor(Math.random() * chars.length));
  }

  return flag + dateCode + randPart;
}

//图标抖动
export function shakeCartIcon() {
  const anim = uni.createAnimation({
    duration: 400,
    timingFunction: "ease",
  });
  anim
    .translateX(-5)
    .step({ duration: 50 })
    .translateX(5)
    .step({ duration: 50 })
    .translateX(-5)
    .step({ duration: 50 })
    .translateX(0)
    .step({ duration: 50 });

  return anim.export();
}

//获取dom
export function getRectDom(selector, content) {
  return new Promise((resolve) => {
    uni
      .createSelectorQuery()
      .in(content || uni)
      .select(selector)
      .boundingClientRect((res) => resolve(res))
      .exec();
  });
}
